import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @className: ExpressionUtil
 * @description:
 * @author: WANGHUI
 * @createDate: 2018/4/18 17:47
 * @version: 1.0
 */
public class ExpressionUtil {


    private static ScriptEngine se  ;

    /*
     * JS ScriptEngine 因初始化过程很耗时，类加载时即完成初始
     */
    static {
        se = new ScriptEngineManager().getEngineByName("javascript");
        String script = " function isTrue( jsonObj , condVal ) {   jsonObj = JSON.parse(jsonObj) ; return eval( condVal ) ; } ";
        try {
            se.eval(script);
        } catch (ScriptException e) {
//            e.printStackTrace();
        }
    }

    public static boolean eval(Object jsonObj, String condVal) throws NoSuchMethodException, ScriptException {
        Invocable jsInvocable = (Invocable) se;
        Object obj = jsInvocable.invokeFunction("isTrue", jsonObj, condVal);
        return (Boolean) obj;
    }

    public static void main(String[] args) throws NoSuchMethodException, ScriptException {
        String jsonStr = "[ { \"info\" : {\"name\":\"wanghui\"} ,\"addr\" :{\"zipCode\":\"12345\"} } ]";
//        Object jsonObj = JSONObject.parse(jsonStr);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            String condVal = "jsonObj[0].info.name == 'wanghui'";
            ExpressionUtil.eval(jsonStr, condVal);
        }
        System.out.println(System.currentTimeMillis() - startTime);

    }
}
